﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit.Design;
using AjaxControlToolkit;
using System.Data;
using BCDataCenter;
using BCDataCenter.BOL;
using CSharp_MessageBox;
using System.Data.SqlClient;

public partial class WebUserControl_BanStartKit : System.Web.UI.UserControl
{
    DataTable dtChiTietDH;
    string error = "";
    BCDataCenter.DataAccessLayer.DAL dt;
    ClassExecute.ClassExecute dtEx;
    string str = BCDataCenter.Configuration.CurrentConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
               
                FillGridHoaDonChuaIn();
                CheckReadOnly();
                FillGrid();
            

            }
            if (gvChiTietDonHang.Rows[0].Cells[0].Text == "Thêm mặt hàng vào hóa đơn")
            {
                int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                gvChiTietDonHang.Rows[0].Cells.Clear();
                gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                txtTongTien.Text = "0";
            }

            //txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");
            string temp = txtNgayHD.Text;
            string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
            AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComLoaiDongIput.ContextKey = day;
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void txtNgayHD_TextChanged(object sender, EventArgs e)
    {
        try
        {
            DateTime date_min = DateTime.Parse(txtNgayMinHD.Value, new CultureInfo("fr-FR", false)).AddDays(1);
            DateTime date_NgayHD = DateTime.Parse(txtNgayHD.Text, new CultureInfo("fr-FR", false));
            if (date_NgayHD < date_min)
            {
                txtNgayHD.Text = date_min.ToString("dd/MM/yyyy");
                uscMsgBox1.AddMessage("Ngày hóa đơn nhỏ hơn ngày khóa sổ '" + date_min.ToString("dd/MM/yyyy") + "'", uscMsgBox.enmMessageType.Error);
                FillGrid();
            }
            string temp = txtNgayHD.Text;
            string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
            AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComLoaiDongIput.ContextKey = day;
            if (Session["RowEditIndexCTDHSK"] != null)
            {
                if (!Session["RowEditIndexCTDHSK"].ToString().Equals("-1"))
                {
                    AutoCompleteExtender AutoComLoaiDongEdit = gvChiTietDonHang.Rows[int.Parse(Session["RowEditIndexCTDHSK"].ToString())].FindControl("txtLoaiDongEdit_AutoCompleteExtender") as AutoCompleteExtender;
                    AutoComLoaiDongEdit.ContextKey = day;
                }
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    private void GetMinDay()
    {
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        try
        {
            txtNgayMinHD.Value = obj.dsMinDay(ref error, Session["Sitecode"].ToString()).Tables[0].Rows[0]["Closed Date"].ToString();

        }
        catch
        { return; }
    }
    public void CheckReadOnly()
    {
        dtEx = new ClassExecute.ClassExecute();
        int i = dtEx.ExecuteSQl_int(str, "[ls_isAllowedChooseInvDate]", CommandType.StoredProcedure, ref error,
            new SqlParameter("@siteCode", Session["sitecode"].ToString()));
        if (i == 0)
        {

            txtNgayHD.Enabled = false;
            txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");
            // GetMinDay();
        }
        else
        {
            txtNgayHD.ReadOnly = false;
            string ClosedDate = dtEx.GetDataDepend(str, "[ls_getClosedDate]", CommandType.StoredProcedure, ref error,
                new SqlParameter("@siteCode", Session["sitecode"].ToString()));
            DateTime date;
            System.Globalization.DateTimeFormatInfo sFormat = new System.Globalization.DateTimeFormatInfo();
            sFormat.ShortDatePattern = "dd/MM/yyyy";
            date = Convert.ToDateTime(ClosedDate, sFormat);
            Session["MinDate"] = date.AddDays(1);
            txtNgayHD.Text = date.AddDays(1).ToString("dd/MM/yyyy");

        }
    }
    private string GetMaHD()
    {
        string MaHD = "";
        try
        {
            BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
            MaHD = obj.dsMatHD(ref error).Tables[0].Rows[0]["MaHD"].ToString();
        }
        catch
        { return MaHD; }
        return MaHD;
    }
    void GetDoanhSoTrongThangTVV(string salesp_key)
    {
        dtEx = new ClassExecute.ClassExecute();
        DataTable dbget = dtEx.Get_Data_DataTable(str, ref error, "ls_getBAMTDInfor", CommandType.StoredProcedure,
            new SqlParameter("@SalesPKey", salesp_key));
        if (dbget.Rows.Count > 0)
        {
            txtDSTrongThang.Text = dbget.Rows[0]["DoanhSoTrongThang"].ToString();
            txtDSTN.Text = dbget.Rows[0]["DoanhSoToanNhom"].ToString();
            txtSoBA.Text = dbget.Rows[0]["SoBAToanNhom"].ToString();
        }
    }

    private bool CheckValid()
    {
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        if (obj.IsExistMaHD(ref error, txtSoHD.Text))
        {
            txtSoHD.Text = GetMaHD();
            uscMsgBox1.AddMessage("Số hóa đơn [" + txtSoHD.Text + "] này đã tồn tại.Bạn phải lưu với số hóa đơn mới [" + obj.dsMatHD(ref error).Tables[0].Rows[0]["MaHD"].ToString() + "]!", uscMsgBox.enmMessageType.Error);
            return false;
        }
        else if (txtMaTVV.Text == "" || txtMaTVV.Text == "null")
        {
            uscMsgBox1.AddMessage("Chưa chọn tư vấn viên.", uscMsgBox.enmMessageType.Error);
            return false;
            //lbMsg.Text = "Số hóa đơn [" + txtSoHD.Text + "] này đã tồn tại.Bạn có muốn lưu với số hóa đơn mới [" + obj.dsMatHD(ref error).Tables[0].Rows[0]["MaHD"].ToString() + "] không?";
        }
        else if (!obj.IsExistTVV(ref error, txtMaTVV.Text))
        {
            uscMsgBox1.AddMessage("Mã tư vấn viên này không tồn tại.", uscMsgBox.enmMessageType.Error);
            return false;
        }

        return true;
    }
    private void FillGridHoaDonChuaIn()
    {
        try
        {
            if (Session["Sitecode"] != null)
            {
                BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
                DataTable dt = obj.dsHoaDonChuaIn(ref error, Session["Sitecode"].ToString(),2).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    gvDonHangChuaIn.DataSource = dt;
                    gvDonHangChuaIn.DataBind();
                }
                else
                {
                    dt.Rows.Add(dt.NewRow());
                    gvDonHangChuaIn.DataSource = dt;
                    gvDonHangChuaIn.DataBind();

                    int TotalColumns = gvDonHangChuaIn.Rows[0].Cells.Count;
                    gvDonHangChuaIn.Rows[0].Cells.Clear();
                    gvDonHangChuaIn.Rows[0].Cells.Add(new TableCell());
                    gvDonHangChuaIn.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                    gvDonHangChuaIn.Rows[0].Cells[0].Text = "Không có đơn hàng chưa in.";
                }

            }
        }
        catch { return; }
    }

    private DataTable dtChiTietDonHang()
    {
        DataTable dtChiTietDH = new DataTable();
        DataColumn dtc;
        //Tao Cot Thu Tu
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "STT";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Loai Dong
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "LoaiDong";
        dtChiTietDH.Columns.Add(dtc);
        //Tao Cot Ma Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "MaHang";
        dtChiTietDH.Columns.Add(dtc);
        //Tao Cot Ten Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "TenHang";
        dtChiTietDH.Columns.Add(dtc);
        //Tao Cot So Luong
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "SoLuong";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Gia
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Gia";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot VAT
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "VAT";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot ThanhTien
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "ThanhTien";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot MaVAT
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "MaVAT";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot loaiKM
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "ProgramType";
        dtChiTietDH.Columns.Add(dtc);

        return dtChiTietDH;
    }
    protected void btnAddRow_Click(object sender, EventArgs e)
    {
        try
        {
            AddRowToGrid();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }

    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        
        
        btnApKhuyenMai_Click(sender, e);
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        dt = new BCDataCenter.DataAccessLayer.DAL();
        string MaHD = "";
        MaHD = GetMaHD();
        try
        {
            if (txtSoHD.Text == "")
            {
                if (CheckValid())
                {
                    double fTongHD = 0;
                    if (txtTongTien.Text != "")
                    {
                        fTongHD = double.Parse(txtTongTien.Text);
                    }
                    DateTime daytimeNow = DateTime.Now;
                    
                    if (obj.InsertHoaDonBanHangTVV(ref error, Session["Sitecode"].ToString(), MaHD, txtMaTVV.Text, Session["username"].ToString(), fTongHD, txtNgayHD.Text, daytimeNow, 2))
                    {
                        dtChiTietDH = (DataTable)Session["dtChiTietDHSK"];
                        int n = dtChiTietDH.Rows.Count;
                        int cout = 0;
                        string DongHang = "";
                        string MaKho = obj.getMaKho(ref error, Session["Sitecode"].ToString());
                        for (int i = 0; i < n; i++)
                        {
                            DongHang = dtChiTietDH.Rows[i]["LoaiDong"].ToString();
                            if (DongHang == "")
                                DongHang = "0";
                            string MaHang = dtChiTietDH.Rows[i]["MaHang"].ToString();

                            string VuotTon = "";
                            if (DongHang != "0")
                            {
                                if (DongHang.Substring(DongHang.Length - 2, 2).Equals("TT"))
                                {
                                    VuotTon = "0";
                                }
                                else
                                {
                                    VuotTon = dt.MyExecuteQuerys(ref error, "P_Get_OverQty", CommandType.StoredProcedure, new SqlParameter("@location", MaKho), new SqlParameter("@qty", int.Parse(dtChiTietDH.Rows[i]["SoLuong"].ToString())), new SqlParameter("@itemkey", MaHang));

                                    //obj.get_VuotTon(ref error, ref VuotTon, MaHang, int.Parse(dtChiTietDH.Rows[i]["SoLuong"].ToString()), MaKho);
                                }
                            }
                            else
                            {
                                VuotTon = dt.MyExecuteQuerys(ref error, "P_Get_OverQty", CommandType.StoredProcedure, new SqlParameter("@location", MaKho), new SqlParameter("@qty", int.Parse(dtChiTietDH.Rows[i]["SoLuong"].ToString())), new SqlParameter("@itemkey", MaHang));
                                //obj.get_VuotTon(ref error, ref VuotTon, MaHang, int.Parse(dtChiTietDH.Rows[i]["SoLuong"].ToString()), MaKho);
                            }

                            if (VuotTon != "")
                            {
                                if (int.Parse(VuotTon) >= 0)
                                {
                                    if (obj.InsertCTHoaDonBanHangTVV(ref error, Session["Sitecode"].ToString(), MaHD, daytimeNow, Session["username"].ToString(),
                                        txtNgayHD.Text, MaHang, dtChiTietDH.Rows[i]["TenHang"].ToString(), DongHang,
                                        dtChiTietDH.Rows[i]["MaVAT"].ToString(), float.Parse(dtChiTietDH.Rows[i]["SoLuong"].ToString()), float.Parse(dtChiTietDH.Rows[i]["Gia"].ToString()),
                                        int.Parse(dtChiTietDH.Rows[i]["STT"].ToString())))
                                    {
                                        cout++;
                                    }
                                    else
                                    {
                                        obj.DeleteCTHoaDonBanHangTVV(ref error, MaHD);
                                        obj.DeleteHoaDonBanHangTVV(ref error, MaHD);
                                        uscMsgBox1.AddMessage("Không thể lưu hóa đơn này.\n Lỗi: " + error, uscMsgBox.enmMessageType.Error);
                                        break;
                                    }
                                }
                                else
                                {
                                    obj.DeleteCTHoaDonBanHangTVV(ref error, MaHD);
                                    obj.DeleteHoaDonBanHangTVV(ref error, MaHD);
                                    uscMsgBox1.AddMessage("Không thể lưu hóa đơn này.Mat hàng [" + MaHang + "] đã vượt tồn kho: " + VuotTon, uscMsgBox.enmMessageType.Error);
                                    break;
                                }
                            }
                        }
                        if (cout == n)
                        {
                            txtSoHD.Text = MaHD;
                            FillGridHoaDonChuaIn();
                            uscMsgBox1.AddMessage("Lưu hóa đơn thành công", uscMsgBox.enmMessageType.Success);
                           
                            BCDataCenter.DataAccessLayer.DAL them = new BCDataCenter.DataAccessLayer.DAL();
                            them.IsExistFromSQL("update ARHDR set doctot =" + float.Parse(txtTongTien.Text) + "where tranno ='" + MaHD + "'", CommandType.Text, ref error);
                        }
                    }
                }
            }
            else //Update
            {
                bool flagVuotTon = false;
                DataTable dtCTHD = new DataTable();
                dtCTHD = (DataTable)Session["dtChiTietDHSK"];
                string VuotTon = "";
                string DongHang = "";
                string MaKho = obj.getMaKho(ref error, Session["Sitecode"].ToString());
                for (int i = 0; i < dtCTHD.Rows.Count; i++)
                {
                    DongHang = dtCTHD.Rows[i]["LoaiDong"].ToString();
                    if (!dtCTHD.Rows[i]["MaHang"].ToString().Equals(""))
                    {
                        VuotTon = dt.MyExecuteQuerys(ref error, "P_Get_OverQty", CommandType.StoredProcedure, new SqlParameter("@location", MaKho), new SqlParameter("@qty", int.Parse(dtCTHD.Rows[i]["SoLuong"].ToString())), new SqlParameter("@itemkey", dtCTHD.Rows[i]["MaHang"].ToString()));
                        //obj.get_VuotTon(ref error, ref VuotTon, dtCTHD.Rows[i]["MaHang"].ToString(), int.Parse(dtCTHD.Rows[i]["SoLuong"].ToString()), MaKho);
                    }
                    else
                    {
                        VuotTon = "0";
                    }

                    if (int.Parse(VuotTon) < 0)
                    {
                        flagVuotTon = true;
                        uscMsgBox1.AddMessage("Không thể lưu hóa đơn này.Mat hàng [" + dtCTHD.Rows[i]["MaHang"].ToString() + "] đã vượt tồn kho: " + VuotTon, uscMsgBox.enmMessageType.Error);
                        break;
                    }
                }
                if (!flagVuotTon)
                {

                    DateTime DateTimeNow = DateTime.Now;
                    string Sitecode = Session["Sitecode"].ToString();
                    string UserName = Session["username"].ToString();

                    //MaHD, NgayHD
                    DataColumn dtc;
                    //Tao Cot DateTimeNow
                    if (!dtCTHD.Columns.Contains("DateTimeNow"))
                    {
                        dtc = new DataColumn();
                        dtc.DataType = Type.GetType("System.String");
                        dtc.ColumnName = "DateTimeNow";
                        dtCTHD.Columns.Add(dtc);
                    }
                    if (!dtCTHD.Columns.Contains("Sitecode"))
                    {
                        dtc = new DataColumn();
                        dtc.DataType = Type.GetType("System.String");
                        dtc.ColumnName = "Sitecode";
                        dtCTHD.Columns.Add(dtc);
                    }
                    if (!dtCTHD.Columns.Contains("UserName"))
                    {
                        dtc = new DataColumn();
                        dtc.DataType = Type.GetType("System.String");
                        dtc.ColumnName = "UserName";
                        dtCTHD.Columns.Add(dtc);
                    }
                    if (!dtCTHD.Columns.Contains("MaHD"))
                    {
                        dtc = new DataColumn();
                        dtc.DataType = Type.GetType("System.String");
                        dtc.ColumnName = "MaHD";
                        dtCTHD.Columns.Add(dtc);
                    }
                    if (!dtCTHD.Columns.Contains("NgayHD"))
                    {
                        dtc = new DataColumn();
                        dtc.DataType = Type.GetType("System.String");
                        dtc.ColumnName = "NgayHD";
                        dtCTHD.Columns.Add(dtc);
                    }

                    for (int i = 0; i < dtCTHD.Rows.Count; i++)
                    {
                        dtCTHD.Rows[i]["DateTimeNow"] = DateTimeNow;
                        dtCTHD.Rows[i]["Sitecode"] = Sitecode;
                        dtCTHD.Rows[i]["UserName"] = UserName;
                        dtCTHD.Rows[i]["MaHD"] = txtSoHD.Text;
                        dtCTHD.Rows[i]["NgayHD"] = txtNgayHD.Text;
                        if (dtCTHD.Rows[i]["LoaiDong"].ToString() == "")
                        {
                            dtCTHD.Rows[i]["LoaiDong"] = "0";
                        }
                    }
                    if (obj.UpdateChiTietHDTVV(ref error, txtSoHD.Text, dtCTHD))
                    {
                        if (obj.UpdateHoaDonTVV(ref error, txtSoHD.Text, float.Parse(txtTongTien.Text), txtNgayHD.Text, DateTime.Now))
                        {
                            FillGridHoaDonChuaIn();
                            uscMsgBox1.AddMessage("Cập nhật đơn hàng chi tiết đơn hàng thành công", uscMsgBox.enmMessageType.Success);
                            BCDataCenter.DataAccessLayer.DAL them = new BCDataCenter.DataAccessLayer.DAL();
                            them.IsExistFromSQL("update ARHDR set doctot =" + float.Parse(txtTongTien.Text) + "where tranno ='" + txtSoHD.Text.ToString() + "'", CommandType.Text, ref error);

                        }
                        else
                        {
                            uscMsgBox1.AddMessage("Cập nhật đơn hàng và chi tiết đơn hàng thất bại", uscMsgBox.enmMessageType.Success);
                        }
                    }
                    else
                    {
                        uscMsgBox1.AddMessage("Cập nhật đơn hàng và chi tiết đơn hàng thất bại.\n Error: ", uscMsgBox.enmMessageType.Error);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            obj.DeleteCTHoaDonBanHangTVV(ref error, MaHD);
            obj.DeleteHoaDonBanHangTVV(ref error, MaHD);
            
            BCDataCenter.ClassWriteLogErr obja = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obja.ErrorLog(ex.Message, method);

            return;
            
        }
    }
    protected void btnNew_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            Session["dtChiTietDHSK"] = null;
            Session["dtChiTietDHKhuyenMaiSK"] = null;
            txtSoHD.Text = "";
            txtMaTVV.Text = "";
            txtTenTVV.Text = "";
            txtThongTinTVV.Text = "";
            txtMaTVV.Enabled = true;
            btnDelete.Visible = false;
            //GetMaHD();
            txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtSoBA.Text = "";
            txtDSTN.Text = "";
            txtDSTrongThang.Text = "";
            FillGrid();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void btnDelete_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            //GetMaHD();
            //txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");
            if (txtSoHD.Text == "")
            {
                uscMsgBox1.AddMessage("Bạn chưa chọn hóa đơn cần xóa", uscMsgBox.enmMessageType.Error);
            }
            else
            {
                BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
                if (obj.DeleteHoaDonVaCTHDBanHangTVV(ref error, txtSoHD.Text))
                {
                    uscMsgBox1.AddMessage("Xóa hóa đơn số [" + txtSoHD.Text + "] thành công", uscMsgBox.enmMessageType.Success);
                    Session["dtChiTietDHSK"] = null;
                    Session["dtChiTietDHKhuyenMaiSK"] = null;
                    txtSoHD.Text = "";
                    btnDelete.Visible = false;
                    FillGrid();
                    FillGridHoaDonChuaIn();


                }
                else
                {
                    uscMsgBox1.AddMessage("Xóa hóa đơn số [" + txtSoHD.Text + "] thất bại.\n Lỗi: \n" + error, uscMsgBox.enmMessageType.Success);
                }
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void btnApKhuyenMai_Click(object sender, ImageClickEventArgs e)
    {
        //Luu chitiet xuong user_input
        // Itemkey, Quantity, amount, IPrice, IVAT, ILineDisc
        try
        {
            BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
            DataTable dt = (DataTable)Session["dtChiTietDHSK"];
            int n = dt.Rows.Count;
            if (Session["dtChiTietDHKhuyenMaiSK"] != null)
            {
                DataTable temp = (DataTable)Session["dtChiTietDHKhuyenMaiSK"];
                for (int i = 0; i < temp.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (temp.Rows[i]["LoaiDong"].ToString() == dt.Rows[j]["LoaiDong"].ToString())
                        {
                            dt.Rows.RemoveAt(j);
                        }
                    }
                }
                Session["dtChiTietDHSK"] = dt;
                n = dt.Rows.Count;
                for (int i = 0; i < n; i++)
                {
                    dt.Rows[i]["STT"] = (i + 1).ToString();
                }
            }

            string UserName = Session["username"].ToString();
            if (n > 0 && !dt.Rows[0]["MaHang"].ToString().Equals(String.Empty))
            {
                for (int i = 0; i < n; i++)
                {
                    obj.InsertUserInput(ref error, UserName, dt.Rows[i]["MaHang"].ToString(),
                        float.Parse(dt.Rows[i]["SoLuong"].ToString()), double.Parse(dt.Rows[i]["ThanhTien"].ToString()),
                        float.Parse(dt.Rows[i]["Gia"].ToString()), dt.Rows[i]["MaVAT"].ToString(), i);

                }
                string temp = txtNgayHD.Text;
                string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
                drop_create_OutPut(UserName);
                new Promotion().CalPromotion(day, "123", Session["username"].ToString());
            }
            DataTable dtKhuyenMai = obj.dsHangKhuyenMai(ref error, UserName).Tables[0];
            Session["dtChiTietDHKhuyenMaiSK"] = dtKhuyenMai;
            for (int i = 0; i < dtKhuyenMai.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["STT"] = (n + i + 1).ToString();
                dr["LoaiDong"] = dtKhuyenMai.Rows[i]["LoaiDong"].ToString();
                dr["MaHang"] = dtKhuyenMai.Rows[i]["MaHang"].ToString();
                dr["TenHang"] = dtKhuyenMai.Rows[i]["TenHang"].ToString();
                dr["SoLuong"] = dtKhuyenMai.Rows[i]["SoLuong"].ToString();
                dr["Gia"] = dtKhuyenMai.Rows[i]["Gia"].ToString();
                if (dtKhuyenMai.Rows[i]["VAT"].ToString() != "")
                    dr["VAT"] = dtKhuyenMai.Rows[i]["VAT"].ToString();
                dr["ThanhTien"] = dtKhuyenMai.Rows[i]["ThanhTien"].ToString();
                dr["MaVAT"] = dtKhuyenMai.Rows[i]["MaVAT"].ToString();
                dr["ProgramType"] = dtKhuyenMai.Rows[i]["ProgramType"].ToString();
                dt.Rows.Add(dr);
            }
            Session["dtChiTietDHSK"] = dt;
            FillGrid();
        }
        catch (Exception ex)
        {
            
             BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
             string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
             obj.ErrorLog(ex.Message, method);
            
            return;
        }

    }
    private void drop_create_OutPut(string username)
    {
        BCDataCenter.DataAccessLayer.DAL dt;
        string tableName = username + "OUTPUT";
        string error = "";
        dt = new BCDataCenter.DataAccessLayer.DAL();
        bool isExist = false;
        //Kiem tra xoa va tao table user_OUTPUT
        isExist = dt.IsExistFromSQL("Get_tableName", CommandType.StoredProcedure, ref error, new System.Data.SqlClient.SqlParameter("@usernames", username), new System.Data.SqlClient.SqlParameter("@add", "OUTPUT"));
        if (isExist)
        {
            bool kq = dt.MyExecuteNonQuerys("Drop table " + tableName, CommandType.Text, ref error);
            if (kq)
            {
                if (kq)
                {
                    error = "OK";
                }
            }
        }
        dt.MyExecuteNonQuerys("CREATE TABLE " + tableName + " ([Itemkey] [varchar] (20) NULL ,[Qty] [float] NULL ,[Amt] [float] NULL ,[Disc] [float] NULL ,[ProgramID] [varchar] (20) NULL ,[PayProgramID] [varchar] (20) NULL ,   [ProgramType] [varchar] (10) NULL, Price Float Null, VAT varchar (10) null, LineDisc float null ) ON [PRIMARY]  ", CommandType.Text, ref error);
    }

    protected void txtMaTVV_TextChanged(object sender, EventArgs e)
    {
        try
        {
            if (!txtMaTVV.Text.Equals(String.Empty))
            {
                string str = txtMaTVV.Text;
                int index = str.IndexOf("|");
                txtMaTVV.Text = str.Substring(0, index - 1);
                txtTenTVV.Text = str.Substring(index + 2, str.Length - index - 2);
                BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
                txtThongTinTVV.Text = obj.dsInfoTuVanVien(ref error, txtMaTVV.Text).Tables[0].Rows[0]["ThongTinTVV"].ToString();
                FillGrid();
                string temp = txtNgayHD.Text;
                string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
                AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
                AutoComLoaiDongIput.ContextKey = day;
                if (Session["RowEditIndexCTDHSK"] != null)
                {
                    int Rowindex = int.Parse(Session["RowEditIndexCTDHSK"].ToString());
                    if (Rowindex != -1)
                    {
                        AutoCompleteExtender AutoComLoaiDongEdit = gvChiTietDonHang.Rows[Rowindex].FindControl("txtLoaiDongEdit_AutoCompleteExtender") as AutoCompleteExtender;
                        AutoComLoaiDongEdit.ContextKey = day;
                    }
                }
            }
            GetDoanhSoTrongThangTVV(txtMaTVV.Text);
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void txtSoLuongEdit_TextChanged(object sender, EventArgs e)
    {
        try
        {
            int row_index = (int)Session["RowEditIndexCTDHSK"];
            RowUpdating(row_index);
            string temp = txtNgayHD.Text;
            string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
            AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComLoaiDongIput.ContextKey = day;
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }

    }
    protected void txtLoaiDongInput_TextChanged(object sender, EventArgs e)
    {
        try
        {
            if (gvChiTietDonHang.Rows[0].Cells[0].Text == "Thêm mặt hàng vào hóa đơn")
            {
                int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                gvChiTietDonHang.Rows[0].Cells.Clear();
                gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                txtTongTien.Text = "0";
            }
            TextBox txtLoaiDongEdit = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput") as TextBox;
            if (!txtLoaiDongEdit.Text.Equals(String.Empty))
            {
                string str = txtLoaiDongEdit.Text;
                int index = str.IndexOf("|");
                txtLoaiDongEdit.Text = str.Substring(0, index - 1);
            }
            TextBox txtMaHangInputFocus = gvChiTietDonHang.FooterRow.FindControl("txtMaHangInput") as TextBox;
            txtMaHangInputFocus.Focus();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void txtLoaiDongEdit_TextChanged(object sender, EventArgs e)
    {
        try
        {

            int row_index = (int)Session["RowEditIndexCTDHSK"];
            TextBox txtLoaiDongEdit = gvChiTietDonHang.Rows[row_index].FindControl("txtLoaiDongEdit") as TextBox;
            if (!txtLoaiDongEdit.Text.Equals(String.Empty))
            {
                string str = txtLoaiDongEdit.Text;
                int index = str.IndexOf("|");
                txtLoaiDongEdit.Text = str.Substring(0, index - 1);
            }
            TextBox txtMaHangEditFocus = gvChiTietDonHang.Rows[row_index].FindControl("txtMaHangEdit") as TextBox;
            txtMaHangEditFocus.Focus();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void txtMaHangInput_TextChanged(object sender, EventArgs e)
    {
        try
        {

            if (gvChiTietDonHang.Rows[0].Cells[0].Text == "Thêm mặt hàng vào hóa đơn")
            {
                int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                gvChiTietDonHang.Rows[0].Cells.Clear();
                gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                txtTongTien.Text = "";
            }

            TextBox txtMaMHInput = gvChiTietDonHang.FooterRow.FindControl("txtMaHangInput") as TextBox;
            TextBox txtTenHangInput = gvChiTietDonHang.FooterRow.FindControl("txtTenHangInput") as TextBox;
            TextBox txtSoLuongInput = gvChiTietDonHang.FooterRow.FindControl("txtSoLuongInput") as TextBox;
            TextBox txtLoaiDongInput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput") as TextBox;

            //FillGrid();
            if (!txtMaMHInput.Text.Equals(String.Empty))
            {
                string str = txtMaMHInput.Text;
                int index = str.IndexOf("|");
                if (index == -1)
                {
                    DataTable dtMH = new BWNhapHoaDonBanHang().dsInfoMatHang(ref error, str).Tables[0];
                    if (dtMH.Rows.Count != 0)
                    {
                        txtMaMHInput.Text = dtMH.Rows[0]["MaHang"].ToString();
                        txtTenHangInput.Text = dtMH.Rows[0]["TenHang"].ToString();
                    }
                    else
                    {
                        uscMsgBox1.AddMessage("Không có mặt hàng này.", uscMsgBox.enmMessageType.Error);
                        txtMaMHInput.Focus();
                        return;
                    }
                }
                else
                {
                    txtMaMHInput.Text = str.Substring(0, index - 1);
                    txtTenHangInput.Text = str.Substring(index + 2, str.Length - index - 2);
                }

                txtSoLuongInput.Focus();

            }
            if (txtLoaiDongInput.Text == "null")
            {
                txtLoaiDongInput.Text = "";
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void txtMaHangEdit_TextChanged(object sender, EventArgs e)
    {
        try
        {
            int row_index = (int)Session["RowEditIndexCTDHSK"];
            TextBox txtMaMHEdit = gvChiTietDonHang.Rows[row_index].FindControl("txtMaHangEdit") as TextBox;
            TextBox txtTenHangEdit = gvChiTietDonHang.Rows[row_index].FindControl("txtTenHangEdit") as TextBox;
            TextBox txtSoLuongEdit = gvChiTietDonHang.Rows[row_index].FindControl("txtSoLuongEdit") as TextBox;
            if (!txtMaMHEdit.Text.Equals(String.Empty))
            {
                string str = txtMaMHEdit.Text;
                int index = str.IndexOf("|");
                if (index == -1)
                {
                    DataTable dtMH = new BWNhapHoaDonBanHang().dsInfoMatHang(ref error, str).Tables[0];
                    if (dtMH.Rows.Count != 0)
                    {
                        txtMaMHEdit.Text = dtMH.Rows[0]["MaHang"].ToString();
                        txtTenHangEdit.Text = dtMH.Rows[0]["TenHang"].ToString();
                    }
                    else
                    {
                        uscMsgBox1.AddMessage("Không có mặt hàng này.", uscMsgBox.enmMessageType.Error);
                        txtMaMHEdit.Focus();
                        return;
                    }
                }
                else
                {
                    txtMaMHEdit.Text = str.Substring(0, index - 1);
                    txtTenHangEdit.Text = str.Substring(index + 2, str.Length - index - 2);
                }
                txtSoLuongEdit.Focus();
            }

        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void txtSoLuongInput_TextChanged(object sender, EventArgs e)
    {
        TextBox txtMaHang = gvChiTietDonHang.FooterRow.FindControl("txtMaHangInput") as TextBox;
        TextBox txtSoLuong = gvChiTietDonHang.FooterRow.FindControl("txtSoLuongInput") as TextBox;

        if (!txtMaHang.Text.Equals(string.Empty))
        {
            AddRowToGrid();
        }
        TextBox txtMaHangFocus = gvChiTietDonHang.FooterRow.FindControl("txtMaHangInput") as TextBox;
        txtMaHangFocus.Focus();
        try
        {
            string temp = txtNgayHD.Text;
            string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
            AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComLoaiDongIput.ContextKey = day;
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    private void AddRow(string LoaiDong, string MaHang, string TenHang, string SoLuong)
    {
        if (Session["dtChiTietDHSK"] == null)
        {
            dtChiTietDH = dtChiTietDonHang();
            Session["dtChiTietDHSK"] = dtChiTietDH;
        }
        dtChiTietDH = (DataTable)Session["dtChiTietDHSK"];
        if (dtChiTietDH.Rows.Count > 0 && dtChiTietDH.Rows[0]["MaHang"].ToString().Equals(String.Empty))
        {
            DataTable dtPrice = new BWNhapHoaDonBanHang().dsGia_ThueMH(ref error, MaHang).Tables[0];
            dtChiTietDH.Rows[0]["STT"] = "0";
            dtChiTietDH.Rows[0]["LoaiDong"] = LoaiDong;
            dtChiTietDH.Rows[0]["MaHang"] = MaHang;
            dtChiTietDH.Rows[0]["TenHang"] = TenHang;
            dtChiTietDH.Rows[0]["SoLuong"] = SoLuong;
            
            dtChiTietDH.Rows[0]["Gia"] = dtPrice.Rows[0]["Gia"].ToString();
            dtChiTietDH.Rows[0]["VAT"] = dtPrice.Rows[0]["VAT"].ToString();
            dtChiTietDH.Rows[0]["MaVAT"] = dtPrice.Rows[0]["MaVAT"].ToString();
            double ThanhTien = 0;
            if (LoaiDong.Equals(""))
                ThanhTien = double.Parse(dtPrice.Rows[0]["Gia"].ToString()) * double.Parse(SoLuong) * (1 + double.Parse(dtPrice.Rows[0]["VAT"].ToString()) / 100);
            dtChiTietDH.Rows[0]["ThanhTien"] = ThanhTien.ToString();
            Session["dtChiTietDHSK"] = dtChiTietDH;
            
        }
        else
        {
            DataTable dtPrice = new BWNhapHoaDonBanHang().dsGia_ThueMH(ref error, MaHang).Tables[0];
            DataRow dtr = dtChiTietDH.NewRow();
            dtr["STT"] = (dtChiTietDH.Rows.Count + 1).ToString();
            dtr["LoaiDong"] = LoaiDong;
            dtr["MaHang"] = MaHang;
            dtr["TenHang"] = TenHang;
            dtr["SoLuong"] = SoLuong;
            
            dtr["Gia"] = dtPrice.Rows[0]["Gia"].ToString();
            dtr["VAT"] = dtPrice.Rows[0]["VAT"].ToString();
            dtr["MaVAT"] = dtPrice.Rows[0]["MaVAT"].ToString();
            double ThanhTien = 0;
            if (LoaiDong.Equals(""))
                ThanhTien = double.Parse(dtPrice.Rows[0]["Gia"].ToString()) * double.Parse(SoLuong) * (1 + double.Parse(dtPrice.Rows[0]["VAT"].ToString()) / 100);
            dtr["ThanhTien"] = ThanhTien.ToString();
            dtChiTietDH.Rows.Add(dtr);
            Session["dtChiTietDHSK"] = dtChiTietDH;
            
        }

    }
    private void AddRowToGrid()
    {
        try
        {
            TextBox txtLoaiDong = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput") as TextBox;
            TextBox txtMaHang = gvChiTietDonHang.FooterRow.FindControl("txtMaHangInput") as TextBox;
            TextBox txtTenHang = gvChiTietDonHang.FooterRow.FindControl("txtTenHangInput") as TextBox;
            TextBox txtSoLuong = gvChiTietDonHang.FooterRow.FindControl("txtSoLuongInput") as TextBox;
            if (!txtLoaiDong.Text.Equals("") && !txtLoaiDong.Text.Equals("null"))
            {
                string temp = txtNgayHD.Text;
                string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
                if (!new BWNhapHoaDonBanHang().IsExistKhuyenMai(ref error, txtLoaiDong.Text, day))
                {
                    uscMsgBox1.AddMessage("Chương trình khuyến mãi không tồn tại.", uscMsgBox.enmMessageType.Error);
                    txtLoaiDong.Focus();
                    return;
                }
            }
            else
            {
                txtLoaiDong.Text = "";
            }

            if (txtSoLuong.Text.Substring(0, 1).Equals("0"))
            {
                uscMsgBox1.AddMessage("Bạn phải nhập số vào ô này và số phải lớn hơn 0 và không được để số 0 ở đầu.", uscMsgBox.enmMessageType.Error);
                txtSoLuong.Focus();
                return;
            }
            Match MyRegMatch = Regex.Match(txtSoLuong.Text, @"\d+$");
            if (!MyRegMatch.Success)
            {
                uscMsgBox1.AddMessage("Bạn phải nhập số vào ô này và số phải lớn hơn 0 và không được để số 0 ở đầu.", uscMsgBox.enmMessageType.Error);
                txtSoLuong.Focus();
                return;
            }
            else
            {
                if (int.Parse(txtSoLuong.Text) < 1)
                {
                    uscMsgBox1.AddMessage("Bạn phải nhập số vào ô này và số phải lớn hơn 0 và không được để số 0 ở đầu.", uscMsgBox.enmMessageType.Error);
                    txtSoLuong.Focus();
                    return;
                }
            }
            // get data from controls
            AddRow(txtLoaiDong.Text, txtMaHang.Text, txtTenHang.Text, txtSoLuong.Text);
            FillGrid();


        }
        catch
        {

        }
    }
    private void FillGrid()
    {
        try
        {
            DataTable dt = new DataTable();
            if (Session["dtChiTietDHSK"] == null)
            {
                dt = dtChiTietDonHang();
                Session["dtChiTietDHSK"] = dtChiTietDH;
            }
            else
                dt = (DataTable)Session["dtChiTietDHSK"];
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows.Count == 1 && dt.Rows[0]["MaHang"].ToString().Equals(String.Empty))
                {
                    gvChiTietDonHang.DataSource = dt;
                    gvChiTietDonHang.DataBind();

                    int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                    gvChiTietDonHang.Rows[0].Cells.Clear();
                    gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                    gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                    gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                    txtTongTien.Text = "0";
                }
                else
                {
                    gvChiTietDonHang.DataSource = dt;
                    gvChiTietDonHang.DataBind();
                    if (TongTienHoaDon(dt, "ThanhTien") == 0)
                    {
                        txtTongTien.Text = "0";
                    }
                    else
                    {
                        txtTongTien.Text = String.Format("{0:###,###}", TongTienHoaDon(dt, "ThanhTien"));
                    }
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["LoaiDong"].ToString() != "")
                        {
                            if (dt.Rows[i]["ProgramType"].ToString() != "")
                            {
                                string ProgramType = dt.Rows[i]["ProgramType"].ToString();
                                int lenght = ProgramType.Length;
                                if (lenght > 4)
                                {
                                    if (!ProgramType.Substring(0, 4).Equals("NONE"))
                                    {
                                        LinkButton linkbtnEdit = gvChiTietDonHang.Rows[i].FindControl("LinkButtonEdit") as LinkButton;
                                        linkbtnEdit.Enabled = false;
                                    }
                                }
                                else
                                {
                                    LinkButton linkbtnEdit = gvChiTietDonHang.Rows[i].FindControl("LinkButtonEdit") as LinkButton;
                                    linkbtnEdit.Visible = false;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                gvChiTietDonHang.DataSource = dt;
                gvChiTietDonHang.DataBind();

                int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                gvChiTietDonHang.Rows[0].Cells.Clear();
                gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                txtTongTien.Text = "0";
            }
        }
        catch { return; }
    }
    private double TongTienHoaDon(DataTable dtChiTietHoaDon, string ColumnName)
    {
        double dTongTien = 0;
        if (dtChiTietHoaDon.Rows.Count > 0)
        {
            for (int i = 0; i < dtChiTietHoaDon.Rows.Count; i++)
            {
                if (dtChiTietHoaDon.Rows[i]["LoaiDong"].ToString() == "" || dtChiTietHoaDon.Rows[i]["LoaiDong"].ToString() == "0")
                {
                    dTongTien += double.Parse(dtChiTietHoaDon.Rows[i][ColumnName].ToString());
                }
            }
        }
        return System.Math.Round(dTongTien);
    }
    protected void gvChiTietDonHang_RowEditingRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            gvChiTietDonHang.EditIndex = -1;
            Session["RowEditIndexCTDHSK"] = -1;
            FillGrid();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void gvChiTietDonHang_RowCreated(object sender, GridViewRowEventArgs e)
    {

    }
    protected void gvChiTietDonHang_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            gvChiTietDonHang.EditIndex = e.NewEditIndex;
            Session["RowEditIndexCTDHSK"] = e.NewEditIndex;
            if (txtSoHD.Text != "")
                get_ListChiTietHoaDon(txtSoHD.Text);
            else
                FillGrid();
            string temp = txtNgayHD.Text;
            string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
            AutoCompleteExtender AutoComLoaiDongEdit = gvChiTietDonHang.Rows[e.NewEditIndex].FindControl("txtLoaiDongEdit_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComLoaiDongEdit.ContextKey = day;
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void gvChiTietDonHang_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.Equals("Intsert"))
            {
                AddRowToGrid();
                TextBox txtMaHangFocus = (TextBox)gvChiTietDonHang.FooterRow.FindControl("txtMaHangInput");
                txtMaHangFocus.Focus();
                string temp = txtNgayHD.Text;
                string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
                AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
                AutoComLoaiDongIput.ContextKey = day;
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
        
    }
    private void RowUpdating(int row_index)
    {
        try
        {
            TextBox txtLoaiDong = (TextBox)gvChiTietDonHang.Rows[row_index].FindControl("txtLoaiDongEdit");
            TextBox txtMaDH = (TextBox)gvChiTietDonHang.Rows[row_index].FindControl("txtMaHangEdit");
            TextBox txtSoLuong = (TextBox)gvChiTietDonHang.Rows[row_index].FindControl("txtSoLuongEdit");
            if (!txtLoaiDong.Text.Equals(""))
            {
                string temp = txtNgayHD.Text;
                string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
                if (!new BWNhapHoaDonBanHang().IsExistKhuyenMai(ref error, txtLoaiDong.Text, day))
                {
                    uscMsgBox1.AddMessage("Chương trình khuyến mãi không tồn tại.", uscMsgBox.enmMessageType.Error);
                    return;
                }
            }

            if (txtSoLuong.Text.Substring(0, 1).Equals("0"))
            {
                uscMsgBox1.AddMessage("Bạn phải nhập số vào ô này và số phải lớn hơn 0 và không được để số 0 ở đầu.", uscMsgBox.enmMessageType.Error);
                txtSoLuong.Focus();
                return;
            }

            Match MyRegMatch = Regex.Match(txtSoLuong.Text, @"\d+$");
            if (!MyRegMatch.Success)
            {
                uscMsgBox1.AddMessage("Bạn phải nhập số vào ô này và số phải lớn hơn 0 và không được để số 0 ở đầu.", uscMsgBox.enmMessageType.Error);
                txtSoLuong.Focus();
                return;
            }
            else if (int.Parse(txtSoLuong.Text) < 1)
            {
                uscMsgBox1.AddMessage("Bạn phải nhập số vào ô này và số phải lớn hơn 0 và không được để số 0 ở đầu.", uscMsgBox.enmMessageType.Error);
                txtSoLuong.Focus();
                return;
            }
            else
            {
                dtChiTietDH = (DataTable)Session["dtChiTietDHSK"];
                dtChiTietDH.Rows[row_index]["LoaiDong"] = txtLoaiDong.Text;
                dtChiTietDH.Rows[row_index]["MaHang"] = txtMaDH.Text;
                dtChiTietDH.Rows[row_index]["TenHang"] = ((TextBox)gvChiTietDonHang.Rows[row_index].FindControl("txtTenHangEdit")).Text;
                dtChiTietDH.Rows[row_index]["SoLuong"] = txtSoLuong.Text;
                DataTable dtPrice = new BWNhapHoaDonBanHang().dsGia_ThueMH(ref error, dtChiTietDH.Rows[row_index]["MaHang"].ToString()).Tables[0];
                dtChiTietDH.Rows[row_index]["Gia"] = dtPrice.Rows[0]["Gia"].ToString();
                dtChiTietDH.Rows[row_index]["VAT"] = dtPrice.Rows[0]["VAT"].ToString();
                dtChiTietDH.Rows[row_index]["MaVAT"] = dtPrice.Rows[0]["MaVAT"].ToString();
                double ThanhTien = 0;
                if (txtLoaiDong.Text.Equals(""))
                    ThanhTien = double.Parse(dtPrice.Rows[0]["Gia"].ToString()) * double.Parse(dtChiTietDH.Rows[row_index]["SoLuong"].ToString()) * (1 + double.Parse(dtPrice.Rows[0]["VAT"].ToString()) / 100);
                dtChiTietDH.Rows[row_index]["ThanhTien"] = ThanhTien.ToString();

                Session["dtChiTietDHSK"] = dtChiTietDH;
                gvChiTietDonHang.EditIndex = -1;
                Session["RowEditIndexCTDHSK"] = -1;
                FillGrid();
            }
            TextBox txtMaDHFocus = (TextBox)gvChiTietDonHang.Rows[row_index].FindControl("txtMaHangInput");
            txtMaDHFocus.Focus();
        }
        catch { return; }
    }
    protected void gvChiTietDonHang_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        RowUpdating(e.RowIndex);
        try
        {
            string temp = txtNgayHD.Text;
            string day = temp.Substring(6, 4) + "-" + temp.Substring(3, 2) + "-" + temp.Substring(0, 2);
            AutoCompleteExtender AutoComLoaiDongIput = gvChiTietDonHang.FooterRow.FindControl("txtLoaiDongInput_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComLoaiDongIput.ContextKey = day;
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void gvChiTietDonHang_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            dtChiTietDH = (DataTable)Session["dtChiTietDHSK"];
            dtChiTietDH.Rows.RemoveAt(e.RowIndex);
            for (int i = 0; i < dtChiTietDH.Rows.Count; i++)
            {
                dtChiTietDH.Rows[i]["STT"] = (i + 1).ToString();
            }
            Session["dtChiTietDHSK"] = dtChiTietDH;
            FillGrid();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    private void get_ListChiTietHoaDon(string MaDH)
    {
        try
        {
            BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
            Session["dtChiTietDHSK"] = obj.dsChiTietHoaDon(ref error, MaDH).Tables[0];
            txtSoHD.Text = MaDH;
            FillGrid();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void gvDonHangChuaIn_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridViewRow gvr = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            if (e.CommandName.Equals("Selected"))
            {

                txtSoHD.Text = gvr.Cells[1].Text;
                DataTable dtInfoHDChuaIn = new BWNhapHoaDonBanHang().dsInfoHoaDonChuaIn(ref error, txtSoHD.Text.Trim()).Tables[0];
                txtMaTVV.Text = dtInfoHDChuaIn.Rows[0]["MaTVV"].ToString();
                txtTenTVV.Text = dtInfoHDChuaIn.Rows[0]["TenTVV"].ToString();
                txtThongTinTVV.Text = dtInfoHDChuaIn.Rows[0]["ThongTinTVV"].ToString();
                txtNgayHD.Text = dtInfoHDChuaIn.Rows[0]["NgayHD"].ToString();
                get_ListChiTietHoaDon(gvr.Cells[1].Text);
                txtMaTVV.Enabled = false;
                btnDelete.Visible = true;
                TabContainer1.ActiveTabIndex = 0;
            }
            else if (e.CommandName.Equals("btnPrinted"))
            {
                Session["MaHDPrinte"] = gvr.Cells[1].Text;
                new BWNhapHoaDonBanHang().UpdateHoaDonChuaIn(ref error, gvr.Cells[1].Text);
                FillGridHoaDonChuaIn();
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("window.open('" + Globals.ApplicationPath + "WebMaster/Administrator/BanHangStartKit/Print.aspx','PrintMe', 'height=900px,width=900px,scrollbars=1');");
                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.UpdatePanel1.GetType(), "NewClientScript", sb.ToString(), true);

               
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void btnPrinted_Click(object sender, EventArgs e)
    {

    }
    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        string error = "";
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        try
        {
            if (count == 0)
            {
                count = 10;
            }
            DataTable dt = new DataTable();
            dt = obj.dsFilterListTuVanVien(ref error, prefixText).Tables[0];
            List<string> items = new List<string>(count);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strName = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dt.Rows[i]["MaTenTVV"].ToString(), dt.Rows[i]["MaTenTVV"].ToString());
                items.Add(strName);
            }
            return items.ToArray();
        }
        catch
        {
            return new string[] { "Không có dữ liệu" };
        }
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            dt = new BCDataCenter.DataAccessLayer.DAL();
            dt.MyExecuteNonQuery("RefreshPrice1", CommandType.StoredProcedure, ref error, new SqlParameter("@tranno", txtSoHD.Text.ToString()));
            string tmp = dt.MyExecuteQuerys(ref error, "RefreshPrice2", CommandType.StoredProcedure, new SqlParameter("@tranno", txtSoHD.Text.ToString()));
            if (tmp != "")
            {
                dt.MyExecuteNonQuerys("update arhdr set doctot =" + float.Parse(tmp) + " where tranno='" + txtSoHD.Text.ToString() + "'", CommandType.Text, ref error);
                txtTongTien.Text = tmp;
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
}
